package main

import (
	"database/sql"
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	// 引入数据库驱动注册及初始化
	_ "github.com/go-sql-driver/mysql"
)

var timeLayoutStr = "2006-01-02 15:04:05" //go中的时间格式化必须是这个时间
var timeLayoutStr2 = "2006/1/2 15:04:05"  //格式可以改变,但必须是这个时间

func main() {
	db, err := sql.Open("mysql", "root:123456@tcp(192.168.1.76:3306)/test?charset=utf8")
	if err != nil {
		fmt.Println("failed to open database:", err.Error())
		return
	}
	fmt.Println("链接成功")

	// 2021/1/16
	r := gin.Default()
	v1 := r.Group("/v1")
	{
		v1.GET("/login", login)
		v1.GET("/reg", reg)
		v1.GET("/json", showJson)
		v1.GET("/info", showInfo)
	}
	r.Run(":9521")
	defer db.Close()
}

func login(c *gin.Context) {
	username := c.DefaultQuery("name", "jack")
	password := c.DefaultQuery("password", "123456")
	ts := time.Now().Format(timeLayoutStr2)
	result := map[string]interface{}{
		"errCode":  0,
		"msg":      "登录成功",
		"username": username,
		"password": password,
		"arr":      []string{"hello", "kitty"},
		"data": map[string]interface{}{
			"time": ts,
			"some": "hellokitty",
		},
	}
	c.AsciiJSON(http.StatusOK, result)
}

func reg(c *gin.Context) {
	name := c.DefaultQuery("name", "hello")
	c.String(http.StatusOK, fmt.Sprintf("hello reg ok %s \n", name))
}

func showInfo(c *gin.Context) {
	id := c.Query("id")
	page := c.DefaultQuery("page", "10")
	c.String(http.StatusOK, fmt.Sprintf("HELLO id = %s ; page = %s \n", id, page))
	// fmt.Printf("show shome id = %s; page = %s \n", id, page)
}

func showJson(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"errCode": 0,
		"msg":     "ok",
	})
}
